package com.Xht.www.servlet;

//后端响应查询客户浏览历史的请求

import com.Xht.www.dao.UserBrowsingHistoryDAO;
import com.Xht.www.po.UserBrowsingHistoryPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/getBrowsingHistory")
public class BrowsingHistoryServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 从会话中获取用户ID（这里假设用户ID已在登录时存入会话）
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        if (userId == null) {
            // 如果未找到用户ID，尝试从请求参数中获取
            String userIdParam = request.getParameter("userId");
            if (userIdParam != null && !userIdParam.isEmpty()) {
                try {
                    userId = Integer.parseInt(userIdParam);
                } catch (NumberFormatException e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.println("{\"error\": \"无效的用户ID\"}");
                    return;
                }
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                out.println("{\"error\": \"未登录或用户ID缺失\"}");
                return;
            }
        }

        UserBrowsingHistoryDAO dao = new UserBrowsingHistoryDAO();
        try {
            // 获取用户浏览历史
            List<UserBrowsingHistoryPO> historyList = dao.getBrowsingHistoryByUserId(userId);

            // 将结果转换为JSON格式
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < historyList.size(); i++) {
                UserBrowsingHistoryPO history = historyList.get(i);
                json.append("{")
                        .append("\"merchantId\":").append(history.getMerchantId()).append(",")
                        .append("\"merchantName\":\"").append(escapeJson(history.getMerchantName())).append("\",")
                        .append("\"browsingTime\":\"").append(history.getBrowsingTime()).append("\"")
                        .append("}");
                if (i < historyList.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");

            out.println(json.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("{\"error\": \"数据库错误，请重试\"}");
        }
    }

    // 简单的JSON转义方法
    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}